﻿using MediatR;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;

namespace MXERP.Client
{
    public partial class App
    {
        [Inject]
        public AuthenticationStateProvider AuthenticationStateProvider { get; set; } = default!;
        [Inject]
        public IMediator Mediator { get; set; } = default!;

        private async Task OnNavigateAsync(Microsoft.AspNetCore.Components.Routing.NavigationContext context)
        {
            var path = context.Path;
            if (path == "")
            {
                NavigationManager.NavigateTo("/home");
                path = "home";
            }
            await Mediator.Send(new TabState.SetCurrentUrl.Action("/" + path));
            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            if (authState.User.Identity?.IsAuthenticated is true)
            {
                var routeState = Store.GetState<RouteState>();
                if (!routeState.IsInit)
                {
                    await Mediator.Send(new RouteState.Init.Action());
                    await Mediator.Send(new TabState.Init.Action());
                }
            }
        }
    }
}
